'''
提供Send Email接口

I.解决发件人名称乱码
    from email.header import Header
    address_from = "%s<rick.lv@wiwide.com>" % Header('吕修权', 'utf-8')

II.解决邮件正文乱码
    html_body = MIMEText(mail_body, 'html', "utf-8")
    html_body["Accept-Language"] = "zh-CN"
    html_body["Accept-Charset"] = "ISO-8859-1,utf-8"
'''

import re
import time
import smtplib
import traceback

from email.header import Header
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from tornado.log import gen_log
from tornado.options import options


class EmailClient(object):

    def __init__(self):
        self.logger = gen_log  # debug|info|warning|error
        self.conf = options.config['email_confs']["qy_qq"]
        self.send_msg = options.config['send_msg']

    def send(self, subject, mail_body, receptions, mmid=0):
        """
        发送email邮件
        :subject -> str, 邮件标题
        :mail_body -> str, 邮件正文(html格式)
        :receptions -> list, 接收邮件的邮箱地址
            e.g. ["test1@wiwide.com", "张三<test2@wiwide.com>"]
        :mmid -> 自定义message_id, 只用于log打印
        """
        self.start_time = time.time()
        receptions = self._parse_receptions(receptions, mmid)
        if not receptions:
            return True
        if not self.send_msg:
            self.logger.info('[Pretend Send Email Success][mmid: %s]' % mmid)
            return True
        # 解决发件人名称乱码
        self.account = "%s<%s>" % (Header('内部系统', 'utf-8'), self.conf["account"])
        res = self._send_mail(subject, mail_body, receptions, mmid)
        return res

    def _parse_receptions(self, receptions, mmid):
        result = {}
        email_pattern = (
            r"[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*"
            r"@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?$"
        )
        email_rule = re.compile(email_pattern)
        group_rule = re.compile(r'(.*?)<(.*?)>')
        for group in receptions:
            data = group_rule.findall(group)
            if data:
                name, addr = data[0]
            else:
                name, addr = None, group
            name = name.replace(" ", "") if name else name
            addr = addr.replace(" ", "") if addr else addr
            if not email_rule.match(addr):
                self.logger.error('[Email Address Error][mmid: %s]' % mmid)
                continue
            result[addr] = addr if not name else "%s<%s>" % (Header(name, 'utf-8'), addr)
        return list(result.values())

    def _send_mail(self, subject, mail_body, receptions, mmid):
        s = None
        try:
            msg = MIMEMultipart('alternative')
            mail_body = "" if mail_body is None else mail_body
            html_body = MIMEText(mail_body, 'html', "utf-8")
            html_body["Accept-Language"] = "zh-CN"
            html_body["Accept-Charset"] = "ISO-8859-1,utf-8"
            msg.attach(html_body)
            msg['Subject'] = subject
            msg['From'] = self.account
            msg['To'] = ",".join(receptions)
            s = smtplib.SMTP_SSL(self.conf["address"], self.conf["port"])
            s.login(self.conf["account"], self.conf["passwd"])
            s.sendmail(self.conf["account"], receptions, msg.as_string())
            s.quit()
            sent_time = (time.time() - self.start_time) * 1000
            self.logger.info('[Send Email Success][mmid: %s][%.2fms]' % (mmid, sent_time))
        except BaseException:
            self.logger.error('[Send Email Fail][mmid: %s]' % mmid)
            traceback.print_exc()
            return False
        finally:
            if s is not None:
                s.close()
        return True


# if __name__ == "__main__":
#     client = EmailClient()
#     execution_time = client.send(subject, mail_body, receptions)
